package com.operator.Activitys.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.operator.Activitys.R;
import com.operator.Activitys.activity.base.BaseActivity;
import com.operator.Activitys.adapter.SearchShopAdapter;
import com.operator.Activitys.adapter.base.BaseRecyclerViewAdapter;
import com.operator.Activitys.bean.SearchShop;
import com.operator.Activitys.bean.User;
import com.operator.Activitys.http.manager.UserManager;
import com.operator.Activitys.utils.Constant;
import com.operator.Activitys.utils.JumperUtils;
import com.operator.Activitys.utils.ToastUtils;
import com.zhy.autolayout.AutoRelativeLayout;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 项目名称：金泽云 手机app
 * 类描述：店铺搜索
 * 创建人：张飞祥
 * 创建时间：2018/5/24 8:51
 * 修改人：张飞祥
 * 修改时间：2018/5/24 8:51
 * 修改备注：
 */
public class SearchShopActivity extends BaseActivity implements TextWatcher {

    //返回按钮
    @Bind(R.id.iv_return)
    ImageView ivReturn;
    //标题
    @Bind(R.id.tv_title)
    TextView tvTitle;
    //功能键
    @Bind(R.id.tv_function)
    TextView tvFunction;
    //标题总布局
    @Bind(R.id.app_bar_layout)
    AutoRelativeLayout appBarLayout;
    //搜索框
    @Bind(R.id.et_search_shop)
    EditText etSearchShop;
    @Bind(R.id.iv_search_clear_shop)
    ImageView ivSearchClearShop;
    //搜索显示列表
    @Bind(R.id.rv_search_shop_list)
    RecyclerView rvSearchShopList;

    //初始化网络请求
    public UserManager mApiManager;
    //TODO 当前 内存中 用户信息
    private User mACacheUser = null;
    //搜索店铺适配器
    private SearchShopAdapter mAdapter = null;

    @Override
    protected void initUI() {
        setContentView(R.layout.act_search_shop);

        //网络请求接口 常驻方法
        mApiManager = mApiManager.getUserApiManager(this,this.getTaskId());
        //TODO 获取内存用户实体
        Gson gson = new Gson();
        mACacheUser = gson.fromJson(mACache.getAsJSONObject(Constant.CACHE_USER) + "", User.class);

        //设置标题
        tvTitle.setText("店铺搜索");
        //显示返回按钮
        ivReturn.setVisibility(View.VISIBLE);
        //显示功能按钮
        tvFunction.setVisibility(View.VISIBLE);
        //显示功能按钮 文字
        tvFunction.setText("转账记录");
        //设置状态栏 背景颜色
        appBarLayout.setBackgroundResource(R.color.color_bg_blue);
    }

    @Override
    protected void initData() {
        //搜索框 输入监听
        etSearchShop.addTextChangedListener(this);
    }

    /**
     * 按钮点击事件
     */
    @OnClick({R.id.iv_return,R.id.tv_function,R.id.iv_search_clear_shop})
    public void onBtnClick(View v) {
        switch (v.getId()) {

            case R.id.iv_return:            //返回
                finish();
                break;

            case R.id.tv_function:          //提现记录
                JumperUtils.JumpTo(this,TransferListActivity.class);
                break;

            case R.id.iv_search_clear_shop: //清除搜索内容
                //清空文本
                etSearchShop.setText("");
                //清空数据
                setClearText();
                break;
        }
    }


    /**
     * 提现 报错
     */
    @Subscriber(tag = Constant.BUS_MY_SEARCH_SHOP_ERROR, mode = ThreadMode.MAIN)
    public void initSearchShopError(String httpSearchShopError) {
        //弹出提示
        ToastUtils.showShort(SearchShopActivity.this,"搜索失败，网络连接不稳定！");
    }

    /**
     * 搜索店铺列表 加载
     */
    @Subscriber(tag = Constant.BUS_MY_SEARCH_SHOP, mode = ThreadMode.MAIN)
    public void initSearchShopList(final List<SearchShop> list) {
        //TODO View 非空判断
        if (rvSearchShopList != null) {
            if (list != null && list.size() != 0) {
                //TODO 装填联系人适配器
                mAdapter = new SearchShopAdapter(SearchShopActivity.this, list);
                //TODO 添加适配器到 列表里面
                rvSearchShopList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                rvSearchShopList.setAdapter(mAdapter);

                //item 点击事件
                mAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constant.INTENT_SEARCH_SHOP_BEAN, list.get(position));
                        //跳转 转账页面
                        JumperUtils.JumpTo(SearchShopActivity.this, TransferActivity.class, bundle);
                    }
                });
            } else {
                ToastUtils.showShort(SearchShopActivity.this, "没有搜索到相应的店铺！");
            }
        }
    }

    /**
     * 监听软件盘上面的 删除键
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_DEL && event.getAction() != KeyEvent.ACTION_UP){
            //TODO 事件监听
            String str = etSearchShop.getText().toString();
            //动态判断 当前是否需要隐藏 list 与 删除 键
            if (str.length() < 2){
                setClearText();
            }else{
                //TODO 开始网络请求
                mApiManager.userSearchShop(str,mACacheUser.getStoreName());
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 文本清空 操作
     */
    public void setClearText(){
        //隐藏文本清空 按钮
        ivSearchClearShop.setVisibility(View.GONE);
        //清空 RecyclerView View
        rvSearchShopList.removeAllViews();
        if (mAdapter != null){
            //清空 适配器数据
            mAdapter.removeAllData();
            //刷新 适配器
            mAdapter.notifyDataSetChanged();
        }
    }


    /**
     * 搜索框 输入监听
     * @param charSequence
     * @param i
     * @param i1
     * @param i2
     */
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }
    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }
    @Override
    public void afterTextChanged(Editable editable) {
        if (!"".equals(editable.toString())){
            //TODO 显示清空按钮
            ivSearchClearShop.setVisibility(View.VISIBLE);
            //TODO 开始网络请求
            mApiManager.userSearchShop(editable.toString(),mACacheUser.getStoreName());
        }
    }
}
